package com.lagou.edu.service.impl;

import com.lagou.edu.dao.LagouAuthCodeDao;
import com.lagou.edu.feign.EmailServiceFeign;
import com.lagou.edu.pojo.LagouAuthCode;
import com.lagou.edu.service.AuthCodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.Date;
import java.util.Random;

/**
 * @author Administrator
 */
@Service
public class AuthCodeServiceImpl implements AuthCodeService {

    // 验证码有效时间, 默认10分钟
    @Value("${auth.code.active.time.minutes:10}")
    private int validityActiveTimeMinutes;

    @Autowired
    private EmailServiceFeign emailFeign;

    @Autowired
    private LagouAuthCodeDao dao;

    @Override
    @Transactional
    public boolean createCode(String email) {
        //获得六位随机码
        String code = String.format("%06d", new Random().nextInt(1000000));
        dao.save(LagouAuthCode.builder()
                .code(code)
                .email(email)
                .createtime(new Date())
                .expiretime(new Date(System.currentTimeMillis() + this.getActiveTimeLong())).build());
        return emailFeign.sendMail(email, code);
    }

    /**
     * 0 正确 1 错误 2 超时
     *
     * @param email
     * @param code
     * @return
     */
    @Override
    public int validate(String email, String code) {
        LagouAuthCode authCode = dao.getByEmailAndCodeByExpiretimeDesc(email, code);
        if (authCode == null) {
            return 1;
        }
        return authCode.getExpiretime().getTime() > System.currentTimeMillis() ? 0 : 2;
    }

    private long getActiveTimeLong() {
        return 60 * 1000 * validityActiveTimeMinutes;
    }
}
